import React from 'react';
import { useState, useMemo } from 'react';

function sum(a, b) {
  console.log("sum函数执行了");
  let nowTime = Date.now();
  while (1) {
    if (Date.now() - nowTime > 5000) {
      break;
    }
  }

  return a + b;
}

export default function TestUseMemo() {
  const [count, setCount] = useState(0);

  let a = 123;
  let b = 456;

  if (count % 10 === 0) {
    a += count;
  }

  const result = useMemo(() => {
    return sum(a, b);
  }, [a, b]);   // 这个数组里传的是依赖项, 当a或b的值发生变化时将重新执行useMemo的回调函数


  return (
    <div>
      <h3 style={{color: 'red'}}>result: {result}</h3>
      <h4>计数值count为: {count}</h4>
      <button onClick={() => { setCount(p => p + 1) }}>点我自增</button>
    </div>
  )
}
